import { CloseCircleOutlined } from "@ant-design/icons";
import Card from "@/components/Card";
import { FC, PropsWithChildren, useEffect, useState } from "react";
import {
  Col,
  Row,
  Checkbox,
  Modal,
  Avatar,
  Tooltip,
  Button,
  message
} from "antd";
import TopSearch from "@/components/TopSearch";
import { createdGroup, getFriendList, getFriendlist } from "@/api/xhr/friends";
import { useSelector } from "react-redux";
type TypeGroupComponent = {
  show: boolean;
  setshow: (data: boolean) => void;
  selectedFriend?: Typefriendslist[];
};
type Typefriendslist = {
  id: number;
  name: string;
  avatar: string;
  checked: boolean;
};
const AddGroupComponent: FC<PropsWithChildren<TypeGroupComponent>> = ({
  show,
  setshow,
  selectedFriend
}) => {
  const userinfo = useSelector((state: any) => state.user.userinfo);
  const [searchVal, setSearchVal] = useState("");
  const [friendslist, setfriendslist] = useState<Typefriendslist[]>([]);
  const [selectedfriends, setselectedfriends] = useState<Typefriendslist[]>([]);
  async function handleOk() {
    if (selectedfriends.length < 2) {
      message.error("请至少选择两个好友👯");
      return;
    }
    const res = await createdGroup({
      userList: [
        ...selectedfriends,
        {
          id: userinfo.id,
          name: userinfo.userName,
          avatar: userinfo.userAvatar
        }
      ],
      userName: userinfo.userName,
      groupCreatorId: userinfo.id
    });
    if (res.statusCode == 200) {
      message.success("创建成功开始聊天吧！");
    }
    setshow(false);
  }
  const handleCancel = async () => {
    setshow(false);
  };
  const onChange = (item: Typefriendslist, e) => {
    if (e.target.checked) {
      setfriendslist(
        friendslist.map(data => {
          if (data.id == item.id) {
            return {
              ...data,
              checked: true
            };
          }
          return data;
        })
      );
      setselectedfriends([...selectedfriends, { ...item, checked: true }]);
    } else {
      deleteFriends(item.id);
    }
  };
  useEffect(() => {
    (async function () {
      await friendList();
      if (selectedFriend) {
        setselectedfriends(selectedFriend);
        setfriendslist(friendlist => {
          return friendlist.map(item => {
            if (selectedFriend.find(data => item.id == data.id)) {
              return {
                ...item,
                checked: true
              };
            }
            return item;
          });
        });
      }
    })();
  }, []);
  function deleteFriends(id: number) {
    setselectedfriends(selectedfriends.filter(item => item.id !== id));
    setfriendslist(
      friendslist.map(data => {
        if (data.id == id) {
          return {
            ...data,
            checked: false
          };
        }
        return data;
      })
    );
  }
  async function friendList() {
    const friendslistres = await getFriendList({ userId: userinfo.id });
    setfriendslist(
      friendslistres.data.map(item => {
        return {
          id: item.id,
          name: item.commendName ? item.commendName : item.userName,
          avatar: item.userAvatar,
          checked: selectedfriends.length
            ? (selectedfriends.find(data => data.id == item.id)?.[
                "checked"
              ] as boolean)
            : false
        };
      })
    );
  }
  async function searchFunc(searchvalue: string) {
    if (searchvalue) {
      const res = await getFriendlist({ userId: userinfo.id, searchvalue });
      if (res.statusCode == 200) {
        const friends = res.data.map(item => {
          return {
            id: item.id,
            name: item.commendName ? item.commendName : item.userName,
            avatar: item.userAvatar,
            checked:
              (selectedfriends.find(data => data.id == item.id)?.[
                "checked"
              ] as boolean) ?? false
          };
        });
        setfriendslist(friends);
      }
    } else {
      friendList();
    }
  }
  return (
    <Modal
      title="🤪创建群聊"
      open={show}
      onCancel={handleCancel}
      footer={null}
      className="p-1"
      width={600}
      closable={false}
    >
      <Row className="mt-2" gutter={[8, 0]}>
        <Col span={10} className="h-80">
          <div className="flex flex-col h-full w-full ">
            <TopSearch
              value={searchVal}
              setvalue={setSearchVal}
              searchFunc={searchFunc}
              className="pt-0"
            ></TopSearch>
            <div className="overflow-y-scroll scrollbar-hide w-full scrollbar select-none cursor-auto flex-1 overflow-x-hidden">
              {friendslist.length ? (
                friendslist.map(item => {
                  return (
                    <Checkbox
                      onChange={e => onChange(item, e)}
                      checked={item.checked}
                      className="w-full"
                      key={item.id}
                    >
                      <Card
                        item={item}
                        className="w-[calc(222px-30px)]"
                        controls={{
                          isshowtime: false, //是否显示时间
                          isshowmessage: false, //是否显示消息
                          isnav: false
                        }}
                      ></Card>
                    </Checkbox>
                  );
                })
              ) : (
                <div className="text-sm text-gray-400">暂无数据</div>
              )}
            </div>
          </div>
        </Col>
        <Col span={14} className="flex flex-col">
          <div className="flex flex-col flex-1 relative">
            <div className="flex justify-between ">
              <span className="font-medium">发起群聊</span>
              {selectedfriends.length ? (
                <span className="text-gray-200">
                  已选择{selectedfriends.length}个联系人
                </span>
              ) : (
                <span className="text-gray-200">未选择联系人</span>
              )}
            </div>
            <div className="px-3 py-2 flex flex-wrap overflow-y-scroll scrollbar-hide w-full scrollbar select-none cursor-auto overflow-x-hidden max-h-[350px] ">
              {selectedfriends.length
                ? selectedfriends.map(item => {
                    return (
                      <div
                        className="h-[65px] w-[57px] mt-3 mr-[12px] flex justify-center items-center flex-col"
                        key={item.id}
                      >
                        <div className="relative">
                          <Avatar shape="square" size={48} src={item.avatar} />
                          <CloseCircleOutlined
                            className=" absolute top-0 right-0 translate-x-1/2 -translate-y-1/2"
                            onClick={() => deleteFriends(item.id)}
                          />
                        </div>
                        {item.name?.length > 6 ? (
                          <Tooltip
                            title={item.name}
                            color="#87d068"
                            key="#87d068"
                          >
                            <div className="max-w-full truncate whitespace-nowrap overflow-hidden text-center ">
                              {item.name}
                            </div>
                          </Tooltip>
                        ) : (
                          <div className="w-12 truncate whitespace-nowrap overflow-hidden text-center">
                            {item.name}
                          </div>
                        )}
                      </div>
                    );
                  })
                : ""}
            </div>
            <div className="p-5 flex justify-center absolute bottom-0 left-14">
              <Button value="small" className="mr-4" onClick={handleCancel}>
                取消
              </Button>
              <Button type="primary" value="small" onClick={handleOk}>
                创建
              </Button>
            </div>
          </div>
        </Col>
      </Row>
    </Modal>
  );
};

export default AddGroupComponent;
